/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.service.impl;


import lombok.RequiredArgsConstructor;
import me.zhengjie.pojo.PPInventoryUpdateDto;
import me.zhengjie.pojo.sqlServer.PPInfo;
import me.zhengjie.pojo.sqlServer.PPInventory;
import me.zhengjie.pojo.sqlServer.PpPallet;
import me.zhengjie.repository.PPInfoRepository;
import me.zhengjie.repository.PPInventoryRepository;
import me.zhengjie.repository.PpPalletRepository;
import me.zhengjie.service.PPInventoryService;
import me.zhengjie.service.PPStorageService;
import me.zhengjie.service.dto.PPInventoryDto;
import me.zhengjie.service.dto.PPInventoryQueryCriteria;
import me.zhengjie.service.mapper.PPInventoryMapper;
import me.zhengjie.utils.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xinglin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-08-19
 **/
@Service
@RequiredArgsConstructor
public class PPInventoryServiceImpl implements PPInventoryService {

    private final PPInventoryRepository ppInventoryRepository;
    private final PPInventoryMapper ppInventoryMapper;
    private final PPInfoRepository ppInfoRepository;

//    @Override
//    public PageResult<PPInventoryUI> queryAll(PPInventoryQueryCriteria criteria, Pageable pageable) {
//        criteria.setStayStatus(0);
//        Page<PPInventory> page = ppInventoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
//
//        return PageUtil.toPage(page.map(x -> {
//                    PPInventoryUI ppInventoryUI = new PPInventoryUI();
//                    ppInventoryUI.setId(x.getId());
//                    ppInventoryUI.setBatch(x.getBatch());
//                    ppInventoryUI.setPpBatch(x.getPpBatch());
//                    ppInventoryUI.setPalletCode(x.getPalletCode());
//                    ppInventoryUI.setQty(x.getQty());
//                    ppInventoryUI.setStorageCode(x.getStorageCode());
//                    ppInventoryUI.setPdTime(x.getPdTime());
//                    ppInventoryUI.setExpTime(x.getExpTime());
//                    ppInventoryUI.setLock_status(x.getLockStatus());
//                    return ppInventoryUI;
//
//                }
//
//        ));
//
//
//    }

    @Override
    public PageResult<PPInventoryDto> queryAll(PPInventoryQueryCriteria criteria, Pageable pageable) {
        //只显示未出库的库存
        criteria.setStayStatus(0);
        Page<PPInventory> page = ppInventoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
//        List<PPInventory> ppInventoryList =  page.getContent();
//        for (PPInventory ppInventory : ppInventoryList) {
//            String ppBatch = ppInventory.getPpBatch();
//            int index = ppBatch.indexOf("-");
//            if (index != -1) {
//                ppBatch = ppBatch.substring(0, index);
//            }
//            ppInventory.setPpBatch(ppBatch);
//        }
//
        PageResult<PPInventoryDto> pageResult = PageUtil.toPage(page.map(ppInventoryMapper::toDto));
        return pageResult;

    }


    @Override
    public List<PPInventoryDto> queryAll(PPInventoryQueryCriteria criteria) {
        return ppInventoryMapper.toDto(ppInventoryRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public PPInventoryDto findById(Integer id) {
        PPInventory ppInventory = ppInventoryRepository.findById(id).orElseGet(PPInventory::new);
        ValidationUtil.isNull(ppInventory.getId(), "PpInventory", "id", id);
        return ppInventoryMapper.toDto(ppInventory);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(me.zhengjie.pojo.sqlServer.PPInventory resources) {
        ppInventoryRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(me.zhengjie.pojo.sqlServer.PPInventory resources) {
        PPInventory ppInventory = ppInventoryRepository.findById(resources.getId()).orElseGet(PPInventory::new);
        ValidationUtil.isNull(ppInventory.getId(), "PpInventory", "id", resources.getId());
        ppInventory.copy(resources);

        //ppInfo的信息也要修改
        PPInfo ppInfo = ppInfoRepository.getPPInfoByPpBatch(ppInventory.getPpBatch());
        ppInfo.setPpQty(resources.getQty());

        ppInfoRepository.save(ppInfo);
        ppInventoryRepository.save(ppInventory);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            ppInventoryRepository.deleteById(id);
        }
    }


    @Override
    public void download(List<PPInventoryDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PPInventoryDto ppInventory : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("储位号", ppInventory.getStorageCode());
            map.put("数量", ppInventory.getQty());
            map.put("入库时间", ppInventory.getInBoundTime());
            map.put("出库时间", ppInventory.getOutBoundTime());
            map.put("是否打包", ppInventory.getIsPakage());
            map.put("正常：safe，预警：warning，超期：exp", ppInventory.getDateStatus());
            map.put("产品批次号", ppInventory.getBatch());
            map.put("pp批次号", ppInventory.getPpBatch());
            map.put("载盘编码", ppInventory.getPalletCode());
            map.put("预警时间", ppInventory.getWarningTime());
            map.put("超期时间", ppInventory.getOutTime());
            map.put("生产日期", ppInventory.getPdTime());
            map.put("过期时间", ppInventory.getExpTime());
            map.put("0为在库，1为出库", ppInventory.getStayStatus());
            map.put("0为禁用，1为启用", ppInventory.getLockStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        ppInventoryRepository.deleteById(id);
    }


    /**
     * 根据id和数量更新库存
     *
     * @param ppInventoryUpdateDto 库存更新信息
     */
    @Override
    @Transactional
    public void updateByIdAndQty(PPInventoryUpdateDto ppInventoryUpdateDto) {
        //根据id查找库存信息
        PPInventory ppInventory = ppInventoryRepository.findPPInventoryById(ppInventoryUpdateDto.getId());

        //更新库存数量
        ppInventory.setQty(ppInventoryUpdateDto.getQty());

        //ppInfo的信息也要修改
        PPInfo ppInfo = ppInfoRepository.getPPInfoByPpBatch(ppInventory.getPpBatch());
        ppInfo.setPpQty(ppInventoryUpdateDto.getQty());

        //保存更新后的库存信息和pp信息
        ppInventoryRepository.save(ppInventory);
        ppInfoRepository.save(ppInfo);

    }

    @Override
    @Transactional
    // 根据栈板码删除PPInventory
    public void deleteByPalletCode(String palletCode) {
        ppInventoryRepository.deletePPInventoryByPalletCode(palletCode);
    }





}